package com.tsugun.mediaplayer.presenter.utils

import android.app.WallpaperManager
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.icu.util.Calendar
import android.net.ConnectivityManager
import android.net.Uri
import android.provider.MediaStore
import android.util.DisplayMetrics
import android.util.Log

import com.tsugun.mediaplayer.view.activity.BaseActivity

import java.io.File
import java.io.FileNotFoundException

import com.tsugun.mediaplayer.presenter.utils.LogHelper.TAG

/**
 * 提供系统参数
 * Created by shize on 2017/5/22.
 */

object SystemHelper {

    var mScreensWidth = -1
    var mScreensHeight = -1

    /**
     * 获取屏幕宽
     */
    fun getScreensWidth(activity: BaseActivity): Int {
        if (mScreensWidth == -1) {
            val dm = getDisplayMetrics(activity)
            mScreensWidth = dm.widthPixels
        }
        return mScreensWidth
    }

    /**
     * 获取屏幕高
     */
    fun getScreensHeight(activity: BaseActivity): Int {
        if (mScreensHeight == -1) {
            val dm = getDisplayMetrics(activity)
            mScreensHeight = dm.heightPixels
        }
        return mScreensHeight
    }

    /**
     * 获取显示说明书
     */
    private fun getDisplayMetrics(activity: BaseActivity): DisplayMetrics {
        val dm = DisplayMetrics()
        activity.windowManager.defaultDisplay.getMetrics(dm)
        return dm
    }

    /**
     * 获取系统时间
     */
    val systemTime: String
        get() {
            val strTime: String
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                val c1 = Calendar.getInstance()
                strTime = ConverterHelper.getTimeString(c1.get(Calendar.HOUR_OF_DAY)) + ":" +
                        ConverterHelper.getTimeString(c1.get(Calendar.MINUTE))
            } else {
                val c2 = java.util.Calendar.getInstance()
                strTime = ConverterHelper.getTimeString(c2.get(java.util.Calendar.HOUR_OF_DAY)) + ":" +
                        ConverterHelper.getTimeString(c2.get(java.util.Calendar.MINUTE))
            }
            return strTime
        }

    /**
     * 获取系统日期
     */
    val systemDate: String
        get() {
            val strDate: String
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                val c1 = Calendar.getInstance()
                strDate = (c1.get(Calendar.MONTH) + 1).toString() + "月" + c1.get(Calendar.DAY_OF_MONTH) + "日"
            } else {
                val c2 = java.util.Calendar.getInstance()
                strDate = (c2.get(java.util.Calendar.MONTH) + 1).toString() + "月" + c2.get(java.util.Calendar.DAY_OF_MONTH) + "日"
            }
            return strDate
        }

    /**
     * 获取系统星期
     */
    val systemWeek: String
        get() {
            val strWeek: String
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                val c1 = Calendar.getInstance()
                strWeek = ConverterHelper.getWeekNum(c1.get(Calendar.DAY_OF_WEEK))
            } else {
                val c2 = java.util.Calendar.getInstance()
                strWeek = ConverterHelper.getWeekNum(c2.get(java.util.Calendar.DAY_OF_WEEK))
            }
            return strWeek
        }

    /**
     * 监测网络是否可用
     */
    fun isNetworkAvailable(context: Context): Boolean {
        val connectivityManager = context.getSystemService(
                Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
        if (connectivityManager != null) {
            val networks = connectivityManager.allNetworks
            if (networks != null && networks.isNotEmpty()) {
                for (network in networks) {
                    if (connectivityManager.getNetworkInfo(network).isConnected) {
                        return true
                    }
                }
            }
        }
        return false
    }

    /**
     * 检测是否为wifi

     * @return bool
     */
    fun isWiFi(context: Context): Boolean {
        val connectivityManager = context.getSystemService(
                Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connectivityManager.activeNetworkInfo
        return networkInfo != null && networkInfo.type == ConnectivityManager.TYPE_WIFI
    }

    /**
     * 检测是否为移动数据流量

     * @return bool
     */
    fun isMobile(context: Context): Boolean {
        val connectivityManager = context.getSystemService(
                Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connectivityManager.activeNetworkInfo
        return networkInfo != null && networkInfo.type == ConnectivityManager.TYPE_MOBILE
    }

    /**
     * @return 获取壁纸
     */
    fun getWallpaper(context: Context): Bitmap {
        val wallpaperManager = WallpaperManager.getInstance(context)
        // 获取整张壁纸
        val wallpaperDrawable = wallpaperManager.drawable
        // 转换drawable为bitmap
        return (wallpaperDrawable as BitmapDrawable).bitmap
    }

    /**
     * 删除多媒体数据库中的图片
     */
    fun deleteImageFile(context: Context, file: File) {
        if (file.isFile) {
            val filePath = file.path
            if (filePath.endsWith(ConverterHelper.EX_NAME)) {
                Log.e(TAG, "deleteFile: filePath=" + filePath)
                val res = context.contentResolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        MediaStore.Audio.Media.DATA + "= \"" + filePath + "\"", null)
                if (res > 0) {
                    file.delete()
                    Log.d(TAG, "deleteFile: 删除成功！！")
                } else {
                    file.delete()
                    Log.e(TAG, "图库没有图片缓存信息！！")
                }
            }
        }
    }

    /**
     * 删除多媒体数据库中的音乐
     */
    fun deleteMusicFile(context: Context, file: File) {
        if (file.isFile) {
            val filePath = file.path
            if (filePath.endsWith(".mp3")) {
                Log.e(TAG, "deleteMusicFile: filePath=" + filePath)
                val res = context.contentResolver.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                        MediaStore.Audio.Media.DATA + "=\"" + filePath + "\"", null)
                if (res > 0) {
                    file.delete()
                    Log.d(TAG, "deleteMusicFile: 删除成功！")
                } else {
                    file.delete()
                    Log.e(TAG, "deleteMusicFile: 没有在系统数据库中找到该歌曲！")
                }
            }
        }
    }

    /**
     * 向系统数据库插入数据并更新数据库

     * @param imagePath 图片路径
     * *
     * @param album     专辑名
     */
    fun insertImage(context: Context?, imagePath: String, album: String) {
        if (context == null) {
            Log.e(ContentValues.TAG, "insertImage: 没有发现上下文！！！")
            return
        }
        // 插入数据库
        try {
            Log.d(ContentValues.TAG, "insertImage: imagePath=" + imagePath)
            MediaStore.Images.Media.insertImage(context.contentResolver, imagePath,
                    ConverterHelper.getImageNameByAlbum(album), null)
            Log.d(ContentValues.TAG, "insertImage: 插入成功！")
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }

        // 通知系统更新
        context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.parse("file://" + BaseActivity.CACHE_DIR)))
    }
}
